<template>
  <div class="auth-container">
    <a-tabs v-model:activeKey="activeTab" type="card" @change="handleTabClick" class="auth-tabs">
      <a-tab-pane key="login" tab="login">
        <a-form :model="loginForm" class="auth-form" @finish="handleLogin">
          <a-form-item label="username" name="username">
            <a-input v-model:value="loginForm.username" placeholder="please input username" />
          </a-form-item>
          <a-form-item label="password" name="password">
            <a-input-password v-model:value="loginForm.password" placeholder="please input password" />
          </a-form-item>
           <!-- 验证码 -->
           <a-form-item label="验证码" name="captcha">
            <div class="captcha-container">
              <a-input v-model:value="loginForm.captcha" placeholder="请输入验证码" style="width: 60%;" />
              <img :src="captchaImage" alt="验证码" @click="refreshCaptcha" class="captcha-image" />
            </div>
           </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit" class="auth-button">login</a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="register" tab="register">
        <a-form :model="registerForm" class="auth-form" @finish="handleRegister">
          <a-form-item label="username" name="username">
            <a-input v-model:value="registerForm.username" placeholder="please input username" />
          </a-form-item>
          <a-form-item label="password" name="password">
            <a-input-password v-model:value="registerForm.password" placeholder="please input password" />
          </a-form-item>
          <a-form-item label="role" name="role">
            <a-select v-model:value="registerForm.role" placeholder="please select role">
              <a-select-option value="guest">guest</a-select-option>
              <a-select-option value="coach">coach</a-select-option>
              <a-select-option value="admin">admin</a-select-option>
            </a-select>
          </a-form-item>
           <!-- 验证码 -->
           <a-form-item label="验证码" name="captcha">
            <div class="captcha-container">
              <a-input v-model:value="registerForm.captcha" placeholder="请输入验证码" style="width: 60%;" />
              <img :src="captchaImage" alt="验证码" @click="refreshCaptcha" class="captcha-image" />
            </div>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" html-type="submit" class="auth-button">register</a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import { message } from 'ant-design-vue';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../store/auth';

const loginForm = ref({
  username: '',
  password: '',
  captcha: '', // 新增验证码字段

});

const registerForm = ref({
  username: '',
  password: '',
  role: 'guest', // 默认选择用户角色
  captcha: '', // 新增验证码字段

});

const activeTab = ref<'login' | 'register'>('login');
const authStore = useAuthStore();
const router = useRouter();

// 验证码图片 URL
const captchaImage = ref<string>('/api/auth/checkCode');

// 刷新验证码
const refreshCaptcha = () => {
  captchaImage.value = `/api/auth/checkCode?timestamp=${Date.now()}`;
};

// 初始化验证码
refreshCaptcha();

// 登录逻辑
const handleLogin = async () => {
  try {
    await authStore.login(loginForm.value.username, loginForm.value.password, loginForm.value.captcha);
    message.success('登录成功');
    router.push({ name: 'Home' });
  } catch (error) {
    const axiosError = error as { response: { data: { message: string; code: number } } };
    // console.log(axiosError.response);
    if (axiosError.response?.data?.code === 401) {
      message.error(axiosError.response.data.message || '用户名或密码错误。');
    } else if (axiosError.response?.data?.code === 400) {
      message.error(axiosError.response.data.message || '验证码错误，请重试。');
      loginForm.value.captcha='';
      refreshCaptcha(); // 刷新验证码
    }  else {
      message.error('登录失败，请重试。');
    }
  }
};

// 注册逻辑
const handleRegister = async () => {
  try {
    await authStore.register(
      registerForm.value.username,
      registerForm.value.password,
      registerForm.value.role,
      registerForm.value.captcha
    );
    message.success('注册成功');
    if (registerForm.value.role === 'guest') {
      router.push({ name: 'NonMemberApplication' });
    } else if (registerForm.value.role === 'coach') {
      router.push({ name: 'CreateNews' });
    }
  } catch (error) {
    const axiosError = error as { response: { data: { message: string; code: number } } };
    // console.log(axiosError.response);
    if (axiosError.response?.data?.code === 409) {
      message.error(axiosError.response.data.message || '用户名已存在，请使用其他用户名。');
    } else if (axiosError.response?.data?.code === 400) {
      message.error(axiosError.response?.data.message || '验证码错误，请重试。');
      registerForm.value.captcha='';
      refreshCaptcha(); // 刷新验证码 
    }else {
      message.error('注册失败，请重试。');
    }
  }
};
// 切换标签页时刷新验证码
const handleTabClick = () => {
  loginForm.value = { username: '', password: '', captcha: '' };
  registerForm.value = { username: '', password: '', role: 'guest', captcha: '' };
  refreshCaptcha();
};
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100vh;
  background: url('../static/login.jpg') no-repeat center center/cover;
  padding: 20px;
  box-sizing: border-box;
}

.auth-tabs {
  width: 100%;
  max-width: 400px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  padding: 24px;
  backdrop-filter: blur(10px);
  margin-right: 10%;
  height: 400px;
  overflow: hidden;
  animation: slideIn 0.5s ease-out;
}

.auth-form {
  width: 100%;
}

.auth-button {
  width: 100%;
  margin-top: 16px;
  background: linear-gradient(135deg, #4a4a4a, #2a2a2a);
  border: none;
  color: white;
  font-weight: bold;
  transition: transform 0.2s ease, background 0.3s ease;
}

.auth-button:hover {
  transform: scale(1.05);
  background: linear-gradient(135deg, #2a2a2a, #4a4a4a);
}

.ant-tabs-nav {
  margin-bottom: 24px;
}

.ant-tabs-tab {
  font-size: 16px;
  font-weight: bold;
  color: #666;
}

.ant-tabs-tab-active {
  color: #333 !important;
}

.ant-tabs-ink-bar {
  background: #333;
}

.ant-input, .ant-input-password {
  border-radius: 8px;
  border: 1px solid #ddd;
}

.ant-select-selector {
  border-radius: 8px !important;
  border: 1px solid #ddd !important;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 验证码容器样式 */
.captcha-container {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  gap: 10px; /* 输入框和图片之间的间距 */
}

/* 验证码图片样式 */
.captcha-image {
  width: 120px; /* 图片宽度 */
  height: 40px; /* 图片高度 */
  cursor: pointer; /* 鼠标悬停时显示手型 */
  border-radius: 4px; /* 圆角 */
  border: 1px solid #ddd; /* 边框 */
}
</style>